import { useEffect, useState } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Skeleton } from '@/components/ui/skeleton';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
import { ArrowRight, RefreshCw } from 'lucide-react';
import { Link } from 'react-router-dom';
import { api } from '@/lib/api';
import { toast } from '@/components/ui/sonner';

interface Statistic {
  label: string;
  value: number;
  unit?: string;
  diff?: number;
}

interface RecentRecord {
  id: string;
  moduleName: string;
  basePackage: string;
  databaseType: string;
  enableBlockchain: boolean;
  createdAt: string;
}

const DashboardPage = () => {
  const [stats, setStats] = useState<Statistic[] | null>(null);
  const [records, setRecords] = useState<RecentRecord[]>([]);
  const [loading, setLoading] = useState(false);
  const [errorMessage, setErrorMessage] = useState<string | null>(null);

  const loadData = async () => {
    try {
      setLoading(true);
      setErrorMessage(null);
      const result = await api.post<{ total: number; blockchainEnabled: number; today: number; records: RecentRecord[] }>(
        '/generator/scaffold/stats/query',
        {
          days: 7,
        }
      );

      setStats([
        { label: '今日生成', value: result.today, unit: '次' },
        { label: '累计生成', value: result.total, unit: '次' },
        {
          label: '区块链模块',
          value: result.blockchainEnabled,
          unit: '次',
        },
      ]);
      setRecords(result.records ?? []);
    } catch (error) {
      console.error(error);
      const message = error instanceof Error ? error.message : '加载概览数据失败';
      toast.error(message);
      if (message.includes('403')) {
        setErrorMessage('您暂无权限访问统计数据，请联系管理员授予权限。');
      } else if (message.includes('404')) {
        setErrorMessage('统计接口暂未启用，可能是后端未开启数据库功能。');
      } else {
        setErrorMessage('加载概览数据失败，请稍后重试。');
      }
      // 展示占位数据
      setStats([
        { label: '今日生成', value: 0, unit: '次' },
        { label: '累计生成', value: 0, unit: '次' },
        { label: '区块链模块', value: 0, unit: '次' },
      ]);
      setRecords([]);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadData();
  }, []);

  return (
    <div className="space-y-6">
      {errorMessage ? (
        <Alert variant="destructive">
          <AlertTitle>统计数据不可用</AlertTitle>
          <AlertDescription>{errorMessage}</AlertDescription>
        </Alert>
      ) : null}

      <div className="flex items-center justify-between">
        <div className="text-sm text-muted-foreground">最近 7 天的脚手架生成活动</div>
        <Button variant="ghost" size="sm" onClick={loadData} disabled={loading}>
          <RefreshCw className={loading ? 'mr-2 h-4 w-4 animate-spin' : 'mr-2 h-4 w-4'} /> 刷新
        </Button>
      </div>

      <section className="grid gap-4 md:grid-cols-3">
        {(stats ?? Array.from({ length: 3 })).map((item, index) => (
          <Card key={index} className="border-primary/10 bg-card shadow-sm">
            <CardHeader className="pb-2">
              <CardTitle className="text-sm font-medium text-muted-foreground">
                {item ? item.label : <Skeleton className="h-4 w-24" />}
              </CardTitle>
            </CardHeader>
            <CardContent>
              {item ? (
                <div className="text-3xl font-bold">
                  {item.value}
                  <span className="ml-1 text-sm font-normal text-muted-foreground">{item.unit}</span>
                </div>
              ) : (
                <Skeleton className="h-8 w-20" />
              )}
            </CardContent>
          </Card>
        ))}
      </section>

      <section className="grid gap-4 lg:grid-cols-2">
        <Card className="border-muted bg-card shadow-sm">
          <CardHeader>
            <CardTitle className="flex items-center justify-between text-base font-semibold">
              最近生成
              <Button variant="link" size="sm" className="h-auto p-0" asChild>
                <Link to="/history" className="flex items-center gap-1">
                  查看全部 <ArrowRight className="h-4 w-4" />
                </Link>
              </Button>
            </CardTitle>
          </CardHeader>
          <CardContent>
            {loading ? (
              <div className="space-y-3">
                {Array.from({ length: 5 }).map((_, idx) => (
                  <Skeleton key={idx} className="h-12 w-full" />
                ))}
              </div>
            ) : records.length === 0 ? (
              <div className="flex h-32 items-center justify-center text-sm text-muted-foreground">
                暂无生成记录，立即创建一个脚手架模块吧。
              </div>
            ) : (
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>模块名称</TableHead>
                    <TableHead>基础包</TableHead>
                    <TableHead>数据库</TableHead>
                    <TableHead>区块链</TableHead>
                    <TableHead>时间</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {records.map((record) => (
                    <TableRow key={record.id}>
                      <TableCell className="font-medium">{record.moduleName}</TableCell>
                      <TableCell className="max-w-[180px] truncate text-xs text-muted-foreground">
                        {record.basePackage}
                      </TableCell>
                      <TableCell>{record.databaseType}</TableCell>
                      <TableCell>{record.enableBlockchain ? '是' : '否'}</TableCell>
                      <TableCell className="text-xs text-muted-foreground">
                        {new Date(record.createdAt).toLocaleString()}
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            )}
          </CardContent>
        </Card>

        <Card className="border-dashed bg-muted/30 backdrop-blur">
          <CardHeader>
            <CardTitle className="text-base font-semibold">快速开始</CardTitle>
          </CardHeader>
          <CardContent className="space-y-4 text-sm text-muted-foreground">
            <p>
              只需三步即可生成完整的 CRUD 模块：填写基础信息、粘贴建表 SQL、配置数据库选项，即可在线预览模板文件或直接导出 ZIP。
            </p>
            <Button asChild>
              <Link to="/generate">立即生成</Link>
            </Button>
            <div className="rounded-md border border-dashed border-primary/40 bg-background p-4 text-xs leading-relaxed">
              <p className="font-medium text-primary">技巧</p>
              <p className="mt-1">
                生成 ZIP 后默认保留 60 分钟，可在 <code>application.yml</code> 的
                <code className="mx-1">scaffold.output.ttl-minutes</code> 调整保留时间。
              </p>
            </div>
          </CardContent>
        </Card>
      </section>
    </div>
  );
};

export default DashboardPage;

